package com.harry.utility;

import java.util.Date;

import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.harry.resource.inner.entity.InnerUser;
import com.harry.configuration.ConstSettings;

/**
 * JWT 工具类
 */
@Component
public class JwtUtils {

	public static String calcToken(InnerUser user) throws Exception {
		return JU().__calcToken(user);
	}

	public static String decodeUserIdentify(String token) throws Exception {
		return JU().__decodeUserIdentify(token);
	}

	public static void verifyToken(InnerUser user, String token) throws Exception {
		JU().__verifyToken(user, token);
	}

	public String __calcToken(InnerUser user) throws Exception {
		if (user.getId() == null) {
			throw new Exception("User ID is null.");
		} else {
			Builder bd = JWT.create();
			if (user.getPassword() != null)
				bd.withExpiresAt(new Date(new Date().getTime() + 12 * 60 * 60 * 1000));
			return bd.withAudience(user.getId()).sign(Algorithm.HMAC256(user.toTokenString()));
		}
	}

	public String __decodeUserIdentify(String token) throws Exception {
		try {
			return JWT.decode(token).getAudience().get(0);
		} catch (Exception e) {
			throw ConstSettings.oauthFailError;
		}
	}

	public void __verifyToken(InnerUser user, String token) throws Exception {
		JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.toTokenString())).build();
		try {
			jwtVerifier.verify(token);
		} catch (JWTVerificationException e) {
			throw ConstSettings.oauthFailError;
		}
	}

	private static JwtUtils JU() {
		return BeanCtxUtils.getBeanByType(JwtUtils.class);
	};
}
